package com.i8office.android.zhihuixinwu.ui.dep;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseFragment;
import com.cyan.tools.base.RecyclerArrayAdapter;
import com.cyan.tools.util.RxBus;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.adapter.OfficeNewAdapter;
import com.i8office.android.zhihuixinwu.module.contract.OfficeContract;
import com.i8office.android.zhihuixinwu.module.presenter.OfficePresenter;
import com.zejian.emotionkeyboard.utils.DisplayUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bean.WorkFlow;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import view.recyclerview.CommonAdapter;
import view.recyclerview.ViewHolder;

@ActivityFragmentInject(
        contentViewId = R.layout.fragment_office
)
public class OfficeNewFragment extends BaseFragment<OfficeContract.Presenter> implements OfficeContract.View {
    @BindView(R.id.list)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.empty)
    TextView empty;
    @BindView(R.id.error)
    TextView error;
    @BindView(R.id.quarters)
    RecyclerView mQuarters;
    @BindView(R.id.year_spinner)
    AppCompatSpinner mYearSpinner;
    public boolean is_first = true;
    private OfficeNewAdapter adapter;
    private int pageNumber = 1, pageSize = 10;
    private Observable<String> observable;
    private Disposable disposable;
    private String keyword = null;
    private Observable<String> readObservable;
    private Disposable readDisposable;
    private int firstPage = 1;
    private String mQuarter = "";
    private String mYear;
    private Observable<String> collectObservable;
    private Disposable collectDisposable;

    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);
        initCollect();
        mPresenter = new OfficePresenter(this);
        adapter = new OfficeNewAdapter(getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.tab_top_bg));
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNumber = firstPage;
                getData();
            }
        });

        observable = RxBus.get().register("submitSuccess", String.class);
        disposable = observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(final String data) throws Exception {
                pageNumber = firstPage;
                getData();
            }
        });
        if (getArguments().getBoolean("isNotify", false)) {
            firstPage = 0;
            readObservable = RxBus.get().register("read", String.class);
            readDisposable = readObservable.subscribe(new Consumer<String>() {
                @Override
                public void accept(final String data) throws Exception {
                    pageNumber = firstPage;
                    getData();
                }
            });
        }
        refresh();
    }

    private void initCollect() {
        if (getArguments().getBoolean("is_collect")) {

            final List<String> mYears = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            int yearNow = calendar.get(Calendar.YEAR);

            calendar.set(Calendar.YEAR, 2018);
            int year = calendar.get(Calendar.YEAR);

            mYear = String.valueOf(year);
            for (int i = 0; i < yearNow - year + 1; i++) {
                mYears.add(String.valueOf(year + i));
            }
            int index = mYears.indexOf(String.valueOf(yearNow));
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.item_year_spinner, R.id.year, mYears);
            mYearSpinner.setAdapter(adapter);
            mYearSpinner.setSelection(index != -1 ? index : 0);
            mYearSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    mYear = mYears.get(position);
                    refresh();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
            mQuarters.setVisibility(View.VISIBLE);
            List<String> quarters = new ArrayList<>();
            quarters.add("1,3");
            quarters.add("4,6");
            quarters.add("7,9");
            quarters.add("10,12");
            switch (calendar.get(Calendar.MONTH) + 1) {
                case 1:
                case 2:
                case 3:
                    mQuarter = quarters.get(0);
                    break;
                case 4:
                case 5:
                case 6:
                    mQuarter = quarters.get(1);
                    break;
                case 7:
                case 8:
                case 9:
                    mQuarter = quarters.get(2);
                    break;
                case 10:
                case 11:
                case 12:
                    mQuarter = quarters.get(3);
                    break;
            }
            Resources resources = getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            double w = DisplayUtils.getScreenWidthPixels(getActivity());
            final int width = (int) ((w - DisplayUtils.dp2px(getActivity(), 20) - w / 6d) / 4d);
            mQuarters.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
            mQuarters.setAdapter(new CommonAdapter<String>(getActivity(), R.layout.item_quarter, quarters) {
                @Override
                protected void convert(ViewHolder holder, final String quarter, final int position) {
                    holder.getConvertView().getLayoutParams().width = width;
                    String[] months = quarter.split(",");
                    holder.setText(R.id.content, getString(R.string.month_range, months[0], months[1]));
                    holder.getView(R.id.content).setSelected(mQuarter.equals(quarter));
                    holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mQuarter.equals(quarter)) {
                                return;
                            }
                            mQuarter = quarter;
                            notifyDataSetChanged();
                            refresh();
                        }
                    });
                }
            });
            collectObservable = RxBus.get().register("collect", String.class);
            collectDisposable = collectObservable.subscribe(new Consumer<String>() {
                @Override
                public void accept(final String data) throws Exception {
                    pageNumber = firstPage;
                    getData();
                }
            });
        }
    }

    public void refresh() {
        refreshLayout.setRefreshing(true);
        pageNumber = firstPage;
        getData();
    }

    private void getData() {
        if (getArguments().getBoolean("is_pending", false)) {
            mPresenter.getPendingDep(getMap(keyword));
        } else if (getArguments().getBoolean("is_collect", false)) {
            mPresenter.getFavoriteDepList(getCollectMap(keyword));
        } else {
            mPresenter.getPendingDepDeal(getMap(keyword));
        }
    }

    public String getKeyword() {
        return keyword;
    }

    @Override
    public void toast(String msg) {

    }

    @Override
    public void showResult(final ArrayList<WorkFlow> data) {
        if (is_first) {
            adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    startActivity(new Intent(getActivity(), DetailDepActivity.class)
                            .putExtra("workFlow", adapter.getItem(position))
                            .putExtra("from", "office")
                            .putExtra("isNotify", getArguments().getBoolean("isNotify", false)));
                    //通知点击之后变为已读
                    if (getArguments().getBoolean("isNotify", false)) {
                        Map<String, String> params = new HashMap<>();
                        params.put("mid", adapter.getItem(position).getMessageId());
                        mPresenter.read(params);
                    }
                }
            });
            adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    pageNumber += 1;
                    getData();
                    if (adapter.getCount() % pageSize != 0) {
                        adapter.stopMore();
                    }
                }
            });
            adapter.setError(R.layout.view_more_error).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    adapter.resumeMore();
                }
            });
            adapter.setNoMore(R.layout.view_nomore);
            is_first = false;
        }
        if (pageNumber == firstPage) {
            adapter.clear();
        }
        recyclerView.setVisibility(View.VISIBLE);
        empty.setVisibility(View.GONE);
        error.setVisibility(View.GONE);
        adapter.addAll(data);

    }

    @Override
    public void showUnReadNum(int num) {
        if (getArguments().getBoolean("isNotify", false)) {
            RxBus.get().post("OnGetMsgNum", num);
        }
    }

    @Override
    public void showEmpty() {
        refreshLayout.setRefreshing(false);
        if (adapter.getCount() == 0) {
            adapter.clear();
            empty.setVisibility(View.VISIBLE);
        } else adapter.stopMore();
    }

    @Override
    public void showError() {
        refreshLayout.setRefreshing(false);
        if (adapter.getCount() == 0) {
            adapter.clear();
            error.setVisibility(View.VISIBLE);
        } else adapter.pauseMore();
    }

    @Override
    public void showProgress() {
        if (is_first) {
            error.setVisibility(View.GONE);
            empty.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        }
    }

    @Override
    public void hideProgress() {
        refreshLayout.setRefreshing(false);
    }

    public Map<String, String> getMap(String queryCondition) {
        Map<String, String> param = new HashMap<>();
        param.put("PageNumber", String.valueOf(pageNumber));
        param.put("PageSize", String.valueOf(pageSize));
        if (!TextUtils.isEmpty(queryCondition))
            param.put("Title", queryCondition);
        else if (!TextUtils.isEmpty(keyword))
            param.put("Title", keyword);
        return param;
    }

    public Map<String, String> getCollectMap(String queryCondition) {
        Map<String, String> param = new HashMap<>();
        param.put("PageNumber", String.valueOf(pageNumber));
        param.put("PageSize", String.valueOf(pageSize));
        if (!TextUtils.isEmpty(queryCondition))
            param.put("Title", queryCondition);
        else if (!TextUtils.isEmpty(keyword))
            param.put("Title", keyword);
        if ((!TextUtils.isEmpty(mQuarter)) && (!TextUtils.isEmpty(mYear))) {
            String[] months = mQuarter.split(",");
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, Integer.parseInt(mYear));
            cal.set(Calendar.MONTH, Integer.parseInt(months[0]) - 1);
            int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.MONTH, Integer.parseInt(months[1]) - 1);
            int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            String startTime = getString(R.string.date_range, mYear, months[0], String.valueOf(firstDay));
            String endTime = getString(R.string.date_range, mYear, months[1], String.valueOf(lastDay));
            param.put("StartTime", startTime);
            param.put("EndTime", endTime);
        }
        return param;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("is_first", is_first);
        outState.putInt("pageNumber", pageNumber);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            is_first = savedInstanceState.getBoolean("is_first");
            pageSize = savedInstanceState.getInt("pageNumber");
        }
    }

    @OnClick(R.id.error)
    public void onViewClicked() {
        getData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (readDisposable != null && !readDisposable.isDisposed()) readDisposable.dispose();
        if (collectDisposable != null && !collectDisposable.isDisposed())
            collectDisposable.dispose();
        if (observable != null) RxBus.get().unregister("submitSuccess", observable);
        if (readObservable != null) RxBus.get().unregister("read", readObservable);
        if (collectObservable != null) RxBus.get().unregister("collect", collectObservable);
    }

    public void query(String keyword) {
        this.keyword = keyword;
        pageNumber = firstPage;
        getData();
    }
}
